<template>
    <div class="search" >
        <input placeholder="请输入搜索的关键字或拼音" v-model="keyword"/>
        <ul v-show="keyword" ref="search">
            <li class="search-item border-bottom"  v-for="item of list" :key="item.id" @click="handleCityClick(item.name)">{{ item.name }}</li>
            <li class="search-item border-bottom" v-show = "!list.length">没有找到匹配数据</li>
        </ul>
    </div>
</template>

<script>
import Bscroll from 'better-scroll'
export default {
  props: {
    cities: Object
  },
  data() {
    return {
      keyword: "",
      list: []
    };
  },
  mounted(){
      this.scroll = new Bscroll(this.$refs.search)
  },
  methods:{
	 handleCityClick(city){        
		this.$store.commit("changeCityValue",city)
        this.$router.push("/")        
	}    
  },
  watch: {
    keyword() {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      this.timer = setTimeout(() => {
        const result = [];
        for (let i in this.cities) {
          this.cities[i].forEach(value => {
            if (
              value.spell.indexOf(this.keyword) > -1 ||
              value.name.indexOf(this.keyword) > -1
            ) {
              result.push(value);
            }
          });
        }
        this.list = result;
      }, 100);
    }
  }
};
</script>

<style lang="scss" scoped>
.search {
  background: #00bcd4;
  overflow: hidden;
  input {
    width: 97%;
    height: 0.7rem;
    text-align: center;
    margin-left: .125rem;
    margin-bottom: .1rem;
  }
  ul {
    z-index: 999;
    background: #ccc;
    overflow: auto;
    max-height: 11.83rem;
  }
}
</style>